package com.iculture;

import helper.FBHelper;

import java.util.ArrayList;
import java.util.Hashtable;

import org.json.JSONArray;
import org.json.JSONException;

import com.facebook.Response;
import com.facebook.Session;
import com.facebook.widget.WebDialog;
import com.matchcalendar.R;

import activities.AddMatchGroupActivity;
import activities.GlobalActivity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.res.Configuration;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.Display;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.WindowManager.LayoutParams;

import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import android.widget.Toast;

public class FavoriteListActivity extends GlobalActivity {
	/** Called when the activity is first created. */
	private ProgressDialog progDlg;
	private Dialog myDialog;
	private Button share;
	private Button match;
	private Button ticket;
	private Button love;
	private ImageView cancel;
	private TextView title;
	private TextView time;
	private TextView location;
	private TextView locationName;
	private TextView description;
	private ArrayList<Activity_DataStructure> DataList = new ArrayList<Activity_DataStructure>();
	private String result_json;
	private String myID;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.favorite_list);
		initGlobalView();
		getButtonActivity().setEnabled(false);
		getButtonActivity().setBackgroundResource(R.color.gray5);
		setupViewComponent();
		new GetMyIDFBHelper()
				.ensureSessionOpenAndDoSomething(FavoriteListActivity.this);
	}

	private void setupViewComponent() {
		// result_json = bundle.getString("SEARCH_RESULUT");

		// getJsonbtn = (Button) findViewById(R.id.getJsonbtn);
		// getJsonbtn.setOnClickListener(getJsonbtnOnClick);
		// mBtnProgDlg.setOnClickListener(btnProgDlgOnClkLis);
	}

	@Override
	public void onConfigurationChanged(Configuration newConfig) {
		super.onConfigurationChanged(newConfig);
		if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) {
			Log.v("ola_log", "landscape");
		} else if (newConfig.orientation == Configuration.ORIENTATION_PORTRAIT) {
			Log.v("ola_log", "portrait");
		}
	}

	/*
	 * private Button.OnClickListener getJsonbtnOnClick = new
	 * Button.OnClickListener() {
	 * 
	 * @Override public void onClick(View v) { loader(); } };
	 */

	private void loader() {
		progDlg = new ProgressDialog(FavoriteListActivity.this);
		progDlg.setMessage(getString(R.string.loadingtxt));
		progDlg.setIcon(android.R.drawable.ic_dialog_info);
		progDlg.setCancelable(false);
		progDlg.setProgressStyle(ProgressDialog.STYLE_SPINNER);
		progDlg.setMax(100);
		progDlg.show();
		new GetDataAyncTask().execute();

	}

	private class GetDataAyncTask extends AsyncTask<Void, Void, String> {

		@Override
		protected String doInBackground(Void... params) {
			String json = result_json;
			if (json != null) {
				Activity_DataStructure data = new Activity_DataStructure();
				DataList = data.parseJsonString(json);
				progDlg.setProgress(100);
				progDlg.cancel();
			} else {
				return "Invalid Param";
			}
			return "SUCCESS";
		}

		@Override
		protected void onPostExecute(String result) {

			if (result == "SUCCESS") {
				if (result_json.contains("null")) {
					Toast.makeText(FavoriteListActivity.this, "您目前並無任何我的最愛紀錄!",
							Toast.LENGTH_SHORT).show();
					Intent it = new Intent(FavoriteListActivity.this,
							FirstJsonExUrlActivity.class);
					startActivity(it);
				} else {
					/*
					 * Toast.makeText(FavoriteListActivity.this, "資料載入成功!",
					 * Toast.LENGTH_SHORT).show();
					 */
					final DataArrayAdapter adapter = new DataArrayAdapter(
							FavoriteListActivity.this, R.id.title, DataList);
					ListView listv = (ListView) findViewById(R.id.lv);
					listv.setAdapter(adapter);
					listv.setScrollingCacheEnabled(false);// 解決殘影問題
					listv.setDivider(new ColorDrawable()); // listview間隔顏色
					listv.setDividerHeight(5); // listview間距
					listv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
						public void onItemClick(AdapterView parent, View view,
								final int position, long id) {
							/*
							 * Toast.makeText(FirstJsonExUrlActivity.this,
							 * adapter.getItem(position).title,
							 * Toast.LENGTH_SHORT).show();
							 */
							myDialog = new Dialog(FavoriteListActivity.this,
									R.style.PauseDialog);
							myDialog.setContentView(R.layout.favorite_dialog_layout);
							myDialog.setTitle(R.string.activity_detail);
							title = (TextView) myDialog
									.findViewById(R.id.dialog_title);
							time = (TextView) myDialog
									.findViewById(R.id.dialog_time);
							location = (TextView) myDialog
									.findViewById(R.id.dialog_location);
							locationName = (TextView) myDialog
									.findViewById(R.id.dialog_locationName);
							description = (TextView) myDialog
									.findViewById(R.id.dialog_description);
							share = (BgButton) myDialog
									.findViewById(R.id.btn_share);
							match = (BgButton) myDialog
									.findViewById(R.id.btn_match);
							ticket = (BgButton) myDialog
									.findViewById(R.id.btn_ticket);
							love = (BgButton) myDialog
									.findViewById(R.id.btn_love);
							cancel = (ImageView) myDialog
									.findViewById(R.id.dialog_cancel);

							title.setText("活動名稱:\n"
									+ adapter.getItem(position).title + "\n");
							time.setText("活動時間:\n"
									+ adapter.getItem(position).startEndTime
									+ "\n");
							locationName.setText("活動地點:\n"
									+ adapter.getItem(position).locationName
									+ "\n");
							location.setText("活動地址:\n"
									+ adapter.getItem(position).location + "\n");
							if (adapter.getItem(position).showUnit.length() > 2) {
								location.append("\n表演單位:\n"
										+ adapter.getItem(position).showUnit
										+ "\n");
							}

							description.setText("活動說明:\n"
									+ adapter.getItem(position).descriptionFilterHtml
									+ "\n");

							if (!adapter.getItem(position).webSales
									.contains("http")) {
								ticket.setText("無售票");
								ticket.setEnabled(false);
							}

							cancel.setOnClickListener(new ImageView.OnClickListener() {
								public void onClick(View v) {
									myDialog.cancel();
								}
							});

							Window dialogWindow = myDialog.getWindow();
							WindowManager m = dialogWindow.getWindowManager();
							Display d = m.getDefaultDisplay();
							LayoutParams p = dialogWindow.getAttributes();

							// p.height = (int) (d.getHeight() * 1);
							p.width = (int) (d.getWidth() * 1);
							p.alpha = 1.0f;
							dialogWindow.setAttributes(p);

							share.setOnClickListener(new Button.OnClickListener() {
								public void onClick(View v) {
									/*
									 * Intent it = new
									 * Intent(Search_Result.this,
									 * SearchActivity.class); startActivity(it);
									 */
									System.out.println("UID===========>"
											+ adapter.getItem(position).UID);
									publishFeedDialog(
											adapter.getItem(position).title,
											adapter.getItem(position).imageUrl,
											"http://cloud.culture.tw/frontsite/inquiry/contentListAction.do?method=doFindContent&subMenuId=401&id="
													+ adapter.getItem(position).UID,
											adapter.getItem(position).location,
											adapter.getItem(position).descriptionFilterHtml);
								}
							});
							ticket.setOnClickListener(new Button.OnClickListener() {
								public void onClick(View v) {
									Uri uri = Uri.parse(adapter
											.getItem(position).webSales);
									final Intent it = new Intent(
											Intent.ACTION_VIEW, uri);
									startActivity(it);

								}
							});
							match.setOnClickListener(new Button.OnClickListener() {
								public void onClick(View v) {
									Intent it = new Intent(
											FavoriteListActivity.this,
											AddMatchGroupActivity.class);
									Bundle bundle = new Bundle();

									bundle.putString("ACT_NAME",
											adapter.getItem(position).title);
									bundle.putString("ACT_LOCATION",
											adapter.getItem(position).location);
									bundle.putString("ACT_TIME",
											adapter.getItem(position).time);
									it.putExtras(bundle);
									startActivity(it);
								}
							});
							love.setOnClickListener(new Button.OnClickListener() {
								public void onClick(View v) {
									new Thread(new Runnable() {
										public void run() {
											executeAsyncTask(adapter
													.getItem(position).UID);
										}
									}).start();
								}
							});

							myDialog.setCanceledOnTouchOutside(true);
							myDialog.show();
						}
					});
				}

			} else {
			}
		}

		private void publishFeedDialog(String title, String picture,
				String link, String location, String description) {
			try {
				Bundle params = new Bundle();
				params.putString("name", title);// title
				params.putString("picture",
						"http://cloud.culture.tw/frontsite/images/no-120.gif");
				params.putString("link", link);
				params.putString("caption", location);// caption
				params.putString("description", description);

				WebDialog feedDialog = (new WebDialog.FeedDialogBuilder(
						FavoriteListActivity.this, Session.getActiveSession(),
						params)).setOnCompleteListener(null).build();
				feedDialog.show();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}

	}

	private class GetMyIDFBHelper extends FBHelper {
		private ProgressDialog proDialog;

		@Override
		protected void doAfterEnsureSessionOpen() {
			proDialog = ProgressDialog.show(FavoriteListActivity.this, "資料載入中",
					"正在取得我的最愛列表...");
			proDialog.setCancelable(false);
			fqlQuery("uid", "user", "uid = me()", null, null, null, null);
		}

		@Override
		protected void doAfterFqlQuery(Response response) {
			try {
				JSONArray dataJsonArr = response.getGraphObject()
						.getInnerJSONObject().getJSONArray("data");
				myID = dataJsonArr.getJSONObject(0).getString("uid");
				new Thread(new Runnable() {
					public void run() {
						executeAsyncTask("get");
					}
				}).start();

				proDialog.cancel();
				// Toast.makeText(FirstJsonExUrlActivity.this,
				// myID,Toast.LENGTH_SHORT).show();

			} catch (JSONException e) {
				e.printStackTrace();
			}
		}
	}

	private class GetFavorite extends
			AsyncTask<Hashtable<String, String>, Void, Boolean> {

		@Override
		protected Boolean doInBackground(Hashtable<String, String>... params) {
			Hashtable ht = params[0];
			Boolean result = false;

			String json = HelperHttp.getJSONResponseFromURL(
					"activity_favorite.php", ht);
			if (json != null) {
				result_json = json;
				result = true;

				// progDlg.setProgress(100);
				// progDlg.cancel();
			} else {
				return false;
			}
			return result;
		}

		@Override
		protected void onPostExecute(Boolean result) {

			if (result == true) {
				Toast.makeText(FavoriteListActivity.this, "我的最愛載入成功!",
						Toast.LENGTH_SHORT).show();
				loader();

			} else {
				Toast.makeText(FavoriteListActivity.this, "資料傳送發生錯誤!",
						Toast.LENGTH_SHORT).show();
			}
		}

	}

	private class DelFavorite extends
			AsyncTask<Hashtable<String, String>, Void, Boolean> {

		@Override
		protected Boolean doInBackground(Hashtable<String, String>... params) {
			Hashtable ht = params[0];
			Boolean result = false;

			String json = HelperHttp.getJSONResponseFromURL(
					"activity_favorite.php", ht);
			if (!json.contains("null")) {
				result_json = json;
				result = true;

				// progDlg.setProgress(100);
				// progDlg.cancel();
			} else {
				return false;
			}
			return result;
		}

		@Override
		protected void onPostExecute(Boolean result) {

			if (result == true) {
				Toast.makeText(FavoriteListActivity.this, "刪除成功!",
						Toast.LENGTH_SHORT).show();
				new Thread(new Runnable() {
					public void run() {
						executeAsyncTask("get");
					}
				}).start();
				myDialog.cancel();

			} else {
				Toast.makeText(FavoriteListActivity.this, "資料傳送發生錯誤!",
						Toast.LENGTH_SHORT).show();
			}
		}

	}

	private void executeAsyncTask(String command) {
		Hashtable<String, String> ht = new Hashtable<String, String>();
		if (command.contains("get")) {
			GetFavorite async = new GetFavorite();
			ht.put("fbid", myID);
			ht.put("action", "get");
			Hashtable[] ht_array = { ht };
			async.execute(ht_array);
		} else {
			DelFavorite async = new DelFavorite();
			ht.put("fbid", myID);
			ht.put("uid", command);
			ht.put("action", "del");
			Hashtable[] ht_array = { ht };
			async.execute(ht_array);
		}

	}

}